package com.xiaoyang.ssyx;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @AUTHOR XiaoYang
 * @DATE 2023/7/3-15:31
 * @DESCRIPTION TODO 多任务组合
 *                   allOf:等待所有任务完成
 *                   anyOf:只要有一个任务完成
 */
public class CompletableFutureDemo5 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建线程池（实际中不这么做）
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        System.out.println("main begin...");
        //1 任务1 返回结果 1024
        CompletableFuture<Integer> futureA = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName()+" begin...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int value = 1024;
            System.out.println("任务1 :" + value);
            System.out.println(Thread.currentThread().getName()+" over...");
            return value;
        }, executorService);

        //2 任务2 返回结果 200
        CompletableFuture<Integer> futureB = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName()+" begin...");
            int value = 200;
            System.out.println("任务2 :" + value);
            System.out.println(Thread.currentThread().getName()+" over...");
            return value;
        }, executorService);

        //当前两个任务都完成时执行
        CompletableFuture<Void> all = CompletableFuture.allOf(futureA, futureB);
        all.get();

        System.out.println("main over...");

    }
}
